package com.xiaoger.ssologin.controller;

import com.xiaoger.ssologin.pojo.User;
import com.xiaoger.ssologin.utils.LoginCacheUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

/**
 * @author xjx
 * @date 2022/3/27 12:22
 */
@Controller
@RequestMapping("/login")
public class LoginController {


    /**
     * 模拟用户数据
     */
    private static Set<User> dbUsers;

    static {
        dbUsers = new HashSet<>();
        dbUsers.add(new User(0, "zhang", "12345"));
        dbUsers.add(new User(1, "zhang1", "12345"));
        dbUsers.add(new User(2, "zhang2", "12345"));
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping
    public String doLogin(User user, HttpSession session, HttpServletResponse response) {
        String target = (String) session.getAttribute("target");
        Optional<User> first = dbUsers.stream().filter(dbUsers -> dbUsers.getUserName().equals(user.getUserName()) &&
                dbUsers.getPassword().equals(user.getPassword())).findFirst();
        if (first.isPresent()) {
            //保存用户信息
            String token = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setDomain("xiaoger.cn");
            response.addCookie(cookie);
            LoginCacheUtil.loginUser.put(token, first.get());
            //重定向到target地址
            return "redirect:" + target;
        } else {
            //登录失败
            session.setAttribute("msg", "用户名或者密码错误");
            return "login";
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @GetMapping("/loginOut")
    public String outLogin(@CookieValue(value = "TOKEN") Cookie cookie, @RequestParam String target, HttpServletResponse response) {
        //设置cookie过期时间为0
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        LoginCacheUtil.loginUser.remove(cookie.getValue());
        return "redirect:" + target;
    }

    /**
     * 通过token获取用户信息
     *
     * @param token
     * @return
     */
    @GetMapping("/info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token) {
        if (!StringUtils.isEmpty(token)) {
            User user = LoginCacheUtil.loginUser.get(token);
            return ResponseEntity.ok(user);
        } else {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }
}
